<template>
  <div class="personal-page">
    <!-- 顶部用户信息卡片 -->
    <el-card class="user-card">
      <div class="user-info">
        <el-avatar :size="60" :src="getAvatarUrl(userInfo.first_name)"></el-avatar>
        <div class="info-content">
          <div class="name-section">
            <h2>{{ userInfo.username || '未登录' }}</h2>
            <div class="user-actions">
              <el-button type="text" @click="showEditDialog" icon="el-icon-edit">编辑资料</el-button>
              <el-button type="text" @click="handleLogout" icon="el-icon-switch-button">退出登录</el-button>
            </div>
          </div>
          <div class="user-meta">
            <p>{{ userInfo.is_superuser ? '超级管理员' : userInfo.is_staff ? '管理员' : '普通用户' }}</p>
            <el-tag :type="userInfo.is_active ? 'success' : 'info'" size="small">
              {{ userInfo.is_active ? '在线' : '离线' }}
            </el-tag>
          </div>
        </div>
      </div>
      <div class="user-stats">
        <div class="stat-item">
          <span class="label">注册时间</span>
          <span class="number">{{ userInfo.date_joined ? formatDate(userInfo.date_joined) : '暂无' }}</span>
        </div>
        <div class="stat-item">
          <span class="label">最后登录</span>
          <span class="number">{{ userInfo.last_login ? formatDate(userInfo.last_login) : '暂无' }}</span>
        </div>
      </div>
    </el-card>

    <!-- 设置网格 -->
    <div class="settings-grid">
      <!-- 系统设置 -->
      <el-card class="settings-card">
        <div slot="header">
          <span>系统设置</span>
        </div>
        <el-form :model="settings" label-width="100px">

          <el-form-item label="深色模式">
            <el-switch v-model="settings.darkMode"></el-switch>
          </el-form-item>
          <el-form-item label="语言">
            <el-select v-model="settings.language" placeholder="请选择语言">
              <el-option label="简体中文" value="zh-CN"></el-option>
              <el-option label="English" value="en-US"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="钉钉通知">
            <div class="dingtalk-config">
              <el-switch v-model="dingTalkConfig.isActive" @change="handleDingTalkStatusChange"></el-switch>
              <el-button type="text" @click="showDingTalkConfig" v-if="dingTalkConfig.isActive">
                配置机器人
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 账号安全设置 -->
      <el-card class="security-card">
        <div slot="header">
          <span>账号安全</span>
        </div>
        <el-form :model="securitySettings" label-width="120px">
          <el-form-item label="修改密码">
            <el-button type="primary" @click="showChangePasswordDialog">修改密码</el-button>
          </el-form-item>
          <el-form-item label="两步验证">
            <el-switch v-model="securitySettings.twoFactorAuth"></el-switch>
          </el-form-item>
          <el-form-item label="登录设备管理">
            <el-button type="primary" @click="showDevicesDialog">查看设备</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 偏好网格 -->
    <div class="preferences-grid">
      <!-- 个人偏好设置 -->
      <el-card class="preferences-card">
        <div slot="header">
          <span>个人偏好</span>
        </div>
        <el-form :model="preferences" label-width="120px">
          <el-form-item label="主题色">
            <el-color-picker v-model="preferences.themeColor"></el-color-picker>
          </el-form-item>
          <el-form-item label="字体大小">
            <el-slider v-model="preferences.fontSize" :min="12" :max="20"></el-slider>
          </el-form-item>
          <el-form-item label="消息提醒音">
            <el-switch v-model="preferences.notificationSound"></el-switch>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 最近活动 -->
      <el-card class="activity-card">
        <div slot="header">
          <span>最近活动</span>
          <el-button style="float: right; padding: 3px 0" type="text">查看全部</el-button>
        </div>
        <el-timeline>
          <el-timeline-item
            v-for="(activity, index) in recentActivities"
            :key="index"
            :timestamp="activity.time"
            :type="activity.type">
            {{ activity.content }}
          </el-timeline-item>
        </el-timeline>
      </el-card>
    </div>

    <!-- 系统通知 -->
    <el-card class="notification-card">
      <div slot="header">
        <span>系统通知</span>
        <el-button style="float: right; padding: 3px 0" type="text">全部已读</el-button>
      </div>
      <el-table :data="notifications" style="width: 100%">
        <el-table-column prop="title" label="标题"></el-table-column>
        <el-table-column prop="time" label="时间" width="180"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 'unread' ? 'danger' : 'info'">
              {{ scope.row.status === 'unread' ? '未读' : '已读' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑资料弹窗 -->
    <el-dialog
      title="编辑个人资料"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false">
      <el-form :model="userForm" :rules="rules" ref="userForm" label-width="100px">
        <el-form-item label="头像">
          <div class="avatar-upload-container">
            <el-avatar :size="80" :src="getAvatarUrl(userForm.first_name)"></el-avatar>
            <el-upload
              class="avatar-uploader"
              :action="`${BASE_URL}/user/upload_avatar`"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="uploadHeaders">
              <el-button size="small" type="primary">更换头像</el-button>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        <el-form-item label="全名" prop="last_name">
          <el-input v-model="userForm.last_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 钉钉机器人配置对话框 -->
    <el-dialog
      title="钉钉机器人配置"
      :visible.sync="dingTalkDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="dingTalkForm" :rules="dingTalkRules" ref="dingTalkForm" label-width="100px">
        <el-form-item label="Webhook" prop="webhook">
          <el-input v-model="dingTalkForm.webhook" placeholder="请输入钉钉机器人的Webhook地址"></el-input>
        </el-form-item>
        <el-form-item label="加签密钥" prop="secret">
          <el-input v-model="dingTalkForm.secret" placeholder="请输入钉钉机器人的加签密钥"></el-input>
        </el-form-item>
        <div class="dingtalk-help">
          <a href="https://open.dingtalk.com/document/robots/custom-robot-access" target="_blank" class="help-link">
            <i class="el-icon-question"></i>
            如何接入钉钉机器人？
          </a>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="handleDeleteDingTalkConfig">删 除</el-button>
        <el-button @click="dingTalkDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleDingTalkConfig">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { updateUserInfo } from '@/api/user'
import { formatDate } from '@/utils/date'
import { BASE_URL, DEFAULT_AVATAR } from '@/config'
import { mapState } from 'vuex'
import { getDingTalkConfig, setDingTalkConfig, deleteDingTalkConfig } from '@/api/dingtalk'

export default {
  name: 'PersonalPage',
  data() {
    return {
      userForm: {
        username: '',
        email: '',
        last_name: '',
        first_name: ''
      },
      dialogVisible: false,
      uploadHeaders: {
        Authorization: `Token ${this.$store.state.user.token}`
      },
      uploadUrl: `${BASE_URL}/user/upload_avatar`,
      rules: {
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        last_name: [
          { required: true, message: '请输入全名', trigger: 'blur' }
        ]
      },
      settings: {
        notification: true,
        darkMode: false,
        language: 'zh-CN'
      },
      securitySettings: {
        twoFactorAuth: false
      },
      preferences: {
        themeColor: '#409EFF',
        fontSize: 14,
        notificationSound: true
      },
      recentActivities: [
        {
          content: '登录系统',
          time: '2024-03-20 10:30:00',
          type: 'primary'
        },
        {
          content: '修改了个人资料',
          time: '2024-03-19 15:20:00',
          type: 'success'
        },
        {
          content: '更新了系统设置',
          time: '2024-03-18 09:15:00',
          type: 'warning'
        }
      ],
      notifications: [
        {
          title: '系统更新提醒',
          time: '2024-03-20 10:00:00',
          status: 'unread'
        },
        {
          title: '安全登录提醒',
          time: '2024-03-19 15:30:00',
          status: 'read'
        }
      ],
      dingTalkConfig: {
        isActive: false
      },
      dingTalkDialogVisible: false,
      dingTalkForm: {
        webhook: '',
        secret: ''
      },
      dingTalkRules: {
        webhook: [
          { required: true, message: '请输入Webhook地址', trigger: 'blur' },
          { pattern: /^https:\/\/oapi\.dingtalk\.com\/robot\/send\?access_token=.*$/, message: '请输入有效的钉钉Webhook地址', trigger: 'blur' }
        ],
        secret: [
          { required: true, message: '请输入加签密钥', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapState('user', ['userInfo'])
  },
  created() {
    this.initUserForm()
    this.checkDingTalkConfig()
  },
  methods: {
    formatDate,
    getAvatarUrl(url) {
      if (!url) return DEFAULT_AVATAR
      return `${BASE_URL}${url}`
    },
    initUserForm() {
      this.userForm = {
        username: this.userInfo.username,
        email: this.userInfo.email,
        last_name: this.userInfo.last_name,
        first_name: this.userInfo.first_name
      }
    },
    showEditDialog() {
      this.dialogVisible = true
    },
    async handleSubmit() {
      try {
        await this.$refs.userForm.validate()
        await updateUserInfo(this.userForm)
        // 更新 Vuex 中的用户信息
        await this.$store.dispatch('user/getUserInfo')
        this.$message.success('更新成功')
        this.dialogVisible = false
      } catch (error) {
        if (error.response && error.response.data && error.response.data.message) {
          this.$message.error(error.response.data.message)
        } else {
          this.$message.error('更新失败')
        }
      }
    },
    handleAvatarSuccess(response) {
      const avatarUrl = response.url
      this.userForm.first_name = avatarUrl
      this.$message.success('头像更新成功')
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG/GIF 格式!')
      }
      if (!isLt10M) {
        this.$message.error('上传头像图片大小不能超过 10MB!')
      }
      return isJPG && isLt10M
    },
    async handleLogout() {
      try {
        await this.$confirm('确定要退出登录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        // 调用退出登录接口，更新用户状态
        await this.$store.dispatch('user/logout')
        this.$message.success('退出登录')
        this.$router.push('/login')
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('退出登录失败')
        }
      }
    },
    // 检查钉钉机器人配置
    async checkDingTalkConfig() {
      try {
        const response = await getDingTalkConfig()
        if (response.data) {
          this.dingTalkConfig.isActive = response.data.is_active
          this.dingTalkForm.webhook = response.data.webhook
          this.dingTalkForm.secret = response.data.secret || ''
        }
      } catch (error) {
        console.error('获取钉钉机器人配置失败:', error)
      }
    },

    // 显示钉钉机器人配置对话框
    showDingTalkConfig() {
      this.dingTalkDialogVisible = true
    },

    // 处理钉钉机器人状态变更
    async handleDingTalkStatusChange(value) {
      try {
        if (!value) {
          // 关闭钉钉通知
          await setDingTalkConfig({
            ...this.dingTalkForm,
            is_active: false
          })
          this.$message.success('已关闭钉钉通知')
        } else {
          // 开启钉钉通知
          if (this.dingTalkForm.webhook) {
            // 如果已有配置，直接开启
            await setDingTalkConfig({
              ...this.dingTalkForm,
              is_active: true
            })
            this.$message.success('已开启钉钉通知')
          } else {
            // 如果没有配置，显示配置对话框
            this.showDingTalkConfig()
            // 重置开关状态，因为还没有实际开启
            this.dingTalkConfig.isActive = false
          }
        }
      } catch (error) {
        // 发生错误时重置开关状态
        this.dingTalkConfig.isActive = !value
        const errorMsg = error.response && error.response.data && error.response.data.message
        this.$message.error(errorMsg || '操作失败')
      }
    },

    // 处理钉钉机器人配置
    async handleDingTalkConfig() {
      try {
        await this.$refs.dingTalkForm.validate()
        const response = await setDingTalkConfig({
          ...this.dingTalkForm,
          is_active: true
        })
        if (response.data) {
          this.$message.success('配置成功')
          this.dingTalkDialogVisible = false
          this.dingTalkConfig.isActive = true
        } else {
          this.$message.error(response.message || '配置失败')
        }
      } catch (error) {
        const errorMsg = error.response && error.response.data && error.response.data.message
        this.$message.error(errorMsg || '配置失败')
      }
    },

    // 处理删除钉钉配置
    async handleDeleteDingTalkConfig() {
      try {
        await this.$confirm('确定要删除钉钉机器人吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await deleteDingTalkConfig()
        this.dingTalkConfig.isActive = false
        this.dingTalkForm.webhook = ''
        this.dingTalkForm.secret = ''
        this.dingTalkDialogVisible = false
        this.$message.success('删除成功')
      } catch (error) {
        if (error !== 'cancel') {
          const errorMsg = error.response && error.response.data && error.response.data.message
          this.$message.error(errorMsg || '删除失败')
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.personal-page {
  padding: 24px;
  max-width: 1400px;
  margin: 0 auto;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
  
  .user-card {
    margin-bottom: 24px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    
    .user-info {
      display: flex;
      align-items: center;
      margin-bottom: 16px;
      
      .el-avatar {
        border: 3px solid #fff;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      }
      
      .info-content {
        margin-left: 16px;
        flex: 1;
        
        .name-section {
          display: flex;
          align-items: center;
          gap: 12px;
          margin-bottom: 4px;
          
          h2 {
            margin: 0;
            font-size: 20px;
            color: #303133;
            font-weight: 600;
          }
          
          .user-actions {
            display: flex;
            gap: 8px;
            
            .el-button {
              padding: 4px 8px;
              font-size: 13px;
              
              &:hover {
                color: #409EFF;
              }
            }
          }
        }
        
        .user-meta {
          display: flex;
          align-items: center;
          gap: 8px;
          
          p {
            margin: 0;
            color: #606266;
            font-size: 14px;
          }
          
          .el-tag {
            font-size: 12px;
            padding: 0 6px;
            height: 20px;
            line-height: 18px;
          }
        }
      }
    }
    
    .user-stats {
      display: flex;
      justify-content: space-between;
      border-top: 1px solid #EBEEF5;
      padding-top: 16px;
      
      .stat-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        
        .label {
          color: #909399;
          font-size: 12px;
          margin-bottom: 4px;
        }
        
        .number {
          color: #606266;
          font-size: 14px;
        }
      }
    }
  }
  
  .settings-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 24px;
    margin-bottom: 24px;

    .settings-card,
    .security-card {
      margin-bottom: 0;
    }
  }

  .preferences-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 24px;
    margin-bottom: 24px;

    .preferences-card,
    .activity-card {
      margin-bottom: 0;
    }
  }

  .notification-card {
    margin-bottom: 24px;
  }
}

.avatar-upload-container {
  display: flex;
  align-items: center;
  gap: 16px;
}

.avatar-uploader {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    
    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.dingtalk-config {
  display: flex;
  align-items: center;
  gap: 10px;
  min-height: 32px;
  position: relative;
  
  .el-button {
    position: absolute;
    left: 50px;
  }
}

.dingtalk-help {
  margin-top: 10px;
  text-align: right;
  
  .help-link {
    color: #409EFF;
    text-decoration: none;
    font-size: 14px;
    
    &:hover {
      color: #66b1ff;
    }
    
    .el-icon-question {
      margin-right: 4px;
    }
  }
}
</style>